package com.usian.skill.controller;

import com.usian.skill.mapper.GoodsMapper;
import com.usian.skill.mapper.OrderInfoMapper;
import com.usian.skill.pojo.Goods;
import com.usian.skill.pojo.OrderInfo;
import com.usian.skill.pojo.SkillGoods;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.OrderInfoService;
import com.usian.skill.service.SkillGoodsService;
import com.usian.skill.service.SkillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("Skill")
public class SkillController {

    @Autowired
    private SkillGoodsService skillGoodsService;

    @Autowired
    private SkillOrderService skillOrderService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderInfoService orderInfoService;

    @RequestMapping("skillGoods")
    public String skillGoods(Integer goodsId, HttpSession session, Model model){
        SkillGoods skillGoods=skillGoodsService.getByGoodsId(goodsId);

        //判断是否有库存
        if(skillGoods.getStockCount()<=0){
            model.addAttribute("errmsg","没有库存了e");
            return "miaosha_fail";
        }

        String userId =(String) session.getAttribute("userId");
        //判断一个用户是否重复下单
        SkillOrder skillOrder=skillOrderService.getByUserId(userId,goodsId);

        if(skillOrder!=null){
            model.addAttribute("errmsg","不能重复下单，你个薅羊毛的");
            return "miaosha_fail";
        }

        //生成订单 完成出库
        skillGoodsService.getByIdEdit(skillGoods.getId());

        //完成对订单表的添加
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodsId(goodsId.longValue());
        orderInfo.setUserId(Long.parseLong(userId));
        orderInfo.setGoodsCount(1);
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setDeliveryAddrId(Long.parseLong("0"));
        orderInfo.setGoodsPrice(9.9);

        Goods goods = goodsMapper.selectById(goodsId);
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfoService.save(orderInfo);

        //对skillorder表进行添加
        SkillOrder skillOrder1 = new SkillOrder();
        skillOrder1.setUserId(Long.parseLong(userId));
        skillOrder1.setGoodsId(goodsId.longValue());
        skillOrder1.setOrderId(orderInfo.getId());
        skillOrderService.save(skillOrder1);

        //存域返回
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("goods",goods);
        return "order_detail";
    }
}
